/*
 * Copyright (C) 2008 Romain Guy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.os.Environment;

public final class IOUtilities {
    public static final String PBS_DIR = "/pbs/";
    public static final int IO_BUFFER_SIZE = 4 * 1024;
    
    private static final ArrayList<String> tempFiles = new ArrayList<String>();
    
    public static boolean removeExternalFile(String file) {
        if(file != null) {
            return new File(file).delete();
        }
        return true;
    }
    
    public static boolean removeExternalFile(File file) {
        if(file != null) {
            return file.delete();
        }
        return true;
    }
    
    public static void add2collection(String file) {
        tempFiles.add(file);
    }
    
    public static void storeExternalBitmap(Bitmap source, File destFile) {
        try {
            final FileOutputStream out = new FileOutputStream(destFile);
            source.compress(Bitmap.CompressFormat.PNG, 90, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns an external File object (SDCard usually)
     * ready to go, with the structure ready etc,...
     * 
     * @param file
     * @return
     * @throws IOException
     */
    public static File getExternalFile(String file) throws IOException {
        
        File f = new File(Environment.getExternalStorageDirectory(), PBS_DIR + file);
        
        String state = Environment.getExternalStorageState();
        if(!state.equals(Environment.MEDIA_MOUNTED))  {
            throw new IOException("SD Card is not mounted.  It is " + state + ".");
        }
        
     // make sure the directory we plan to store the recording in exists
        File directory = new File(f.getAbsolutePath()).getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
          throw new IOException("Path to file could not be created.");
        }
        
        return f;
    }

    /**
     * Copy the content of the input stream into the output stream, using a temporary
     * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
     *
     * @param in The input stream to copy from.
     * @param out The output stream to copy to.
     *
     * @throws java.io.IOException If any error occurs during the copy.
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    /**
     * Closes the specified stream.
     *
     * @param stream The stream to close.
     */
    public static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(Global.LOG_TAG, "Could not close stream", e);
            }
        }
    }
    
    public static void cleanUp() {
        android.util.Log.d(Global.LOG_TAG, "Cleaning up temp files...");
        final ArrayList<String> list = tempFiles;
        for(String file : list) {
            removeExternalFile(file);
        }
    }
}
